#include <QtGui>
#include <QtNetwork>
#include <QApplication>
#include "sender.h"

Sender::Sender(QWidget *parent) : QDialog(parent) {
    statusLabel = new QLabel(tr("Ready to broadcast datagrams on port 45454"));

    downButton  = new QPushButton(tr("&Down"));
    upButton    = new QPushButton(tr("&Up"));
    quitButton  = new QPushButton(tr("&Quit"));

    buttonBox = new QDialogButtonBox;
    buttonBox->addButton(downButton, QDialogButtonBox::ActionRole);
    buttonBox->addButton(upButton,   QDialogButtonBox::ActionRole);
    buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole);

    messageNo = 1;

    udpSocket = new QUdpSocket(this);
    
    connect(downButton, SIGNAL(clicked()), this, SLOT(sendDOWN()));
    connect(upButton,   SIGNAL(clicked()), this, SLOT(sendUP()));
    connect(quitButton, SIGNAL(clicked()), this, SLOT(sendQuit()));

    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->addWidget(statusLabel);
    mainLayout->addWidget(buttonBox);
    setLayout(mainLayout);

    setWindowTitle(tr("Broadcast Sender"));
}

void Sender::sendUP(){
    upButton->setEnabled(false);
    downButton->setEnabled(true);
    statusLabel->setText("Sending UP");
    QByteArray message = "UP";
    udpSocket->writeDatagram(message.data(), message.size(),
                             QHostAddress::Broadcast, 45454);
}

void Sender::sendDOWN(){
    upButton->setEnabled(true);
    downButton->setEnabled(false);
    statusLabel->setText("Sending DOWN");
    QByteArray message = "DOWN";
    udpSocket->writeDatagram(message.data(), message.size(),
                             QHostAddress::Broadcast, 45454);
}

void Sender::sendQuit(){
    QByteArray message = "QUIT";
    udpSocket->writeDatagram(message.data(), message.size(),
                             QHostAddress::Broadcast, 45454);
    close();
}
